package com.huaiwei.usmManager.modules.usm.controller;


import com.huaiwei.usmManager.common.utils.Constant;
import com.huaiwei.usmManager.common.utils.R;
import com.huaiwei.usmManager.modules.usm.entity.GoodsEntity;
import com.huaiwei.usmManager.modules.usm.entity.SalesEntity;
import com.huaiwei.usmManager.modules.usm.service.GoodsService;
import com.huaiwei.usmManager.modules.usm.service.SalesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/*
    添加销售记录
    修改销售记录
    删除销售记录
    销售记录列表分页
    销售记录列表筛选
 */

@RestController
@RequestMapping("/sales")
@Api(tags = "销售记录模块")
public class SalesController {

  @Autowired
  private SalesService salesService;

  @Autowired
  private GoodsService goodsService;

  @GetMapping("/info/{salesId}")
  @ApiOperation("根据销售id查询所有信息")
  public R info(@PathVariable("salesId") Integer salesId) {
    return R.ok().put("sale", salesService.getById(salesId));
  }

  @PostMapping("/update")
  @ApiOperation("添加或修改销售记录")
  public R insertOrUpdate(@RequestBody SalesEntity salesEntity) {
    if (salesEntity.getSalesId() == null) {
      GoodsEntity goodsEntity = goodsService.getInfoByGoodsId(salesEntity.getGoodsId());
      int oldNum = goodsEntity.getGoodsNum();
      int newNum = oldNum - salesEntity.getSaleNum();
      if (newNum < 0) {
        return R.error("库存不足！");
      } else {
        salesService.saveOrUpdate(salesEntity);
        goodsEntity.setGoodsNum(newNum);
        goodsService.updateById(goodsEntity);
        return R.ok();
      }
    } else {
      salesService.saveOrUpdate(salesEntity);
      return R.ok();
    }
  }

  @DeleteMapping("/delete/{salesId}")
  @ApiOperation("删除销售记录")
  public R delete(@PathVariable("salesId") Integer salesId) {
    salesService.removeById(salesId);
    return R.ok();
  }

  /*@PostMapping("/status")
  @ApiOperation("修改销售记录状态")
  public R status(@RequestBody SalesEntity salesEntity) {
    salesService.updateById(salesEntity);
    return R.ok();
  }*/

  @GetMapping("/list")
  @ApiOperation("分页查询销售记录列表")
  public R list(@RequestParam Map<String, Object> params) {
    return R.ok().put("page", salesService.queryPage(params));
  }

  @GetMapping("/select")
  @ApiOperation("商品下拉菜单")
  public R select() {
    return R.ok().put("data", salesService.select(Constant.ON));
  }

}
